// API base URL
const API_BASE_URL = 'http://124.222.104.145:8003';

// 获取本地token
const getToken = async () => {
    try {
        const token = await (window?.localStorage?.getItem('api_token') || null);
        return token;
    } catch {
        return null;
    }
};

const getBooks = async () => {
    try {
        const response = await fetch(`${API_BASE_URL}/book/books/`);
        if (!response.ok) {
            throw new Error('获取书籍列表失败');
        }
        const data = await response.json();
        return Array.isArray(data) ? data : [];
    } catch (error) {
        console.error('获取书籍列表失败:', error);
        return [];
    }
};

const searchBooks = async (params) => {
    try {
        const queryString = new URLSearchParams(params).toString();
        const headers = {
            'Content-Type': 'application/json',
        };
        const response = await fetch(`${API_BASE_URL}/book/search/?${queryString}`, {
            method: 'GET',
            headers,
        });
        if (!response.ok) {
            throw new Error('搜索书籍失败');
        }
        const data = await response.json();
        // 兼容后端返回格式
        if (Array.isArray(data.books)) return data.books;
        if (Array.isArray(data)) return data;
        return [];
    } catch (error) {
        console.error('搜索书籍失败:', error);
        return [];
    }
};

const getHotBooks = async () => {
    try {
        const response = await fetch(`${API_BASE_URL}/book/hot-books/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (!response.ok) {
            throw new Error('获取热门书籍失败');
        }

        const data = await response.json();
        return Array.isArray(data) ? data : [];
    } catch (error) {
        console.error('获取热门书籍失败:', error);
        return [];
    }
};

export { getBooks, searchBooks, getHotBooks }; 